package com.zkw.aio;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
import java.nio.charset.Charset;
import java.util.concurrent.CountDownLatch;

/**
 * Created by Administrator on 2016/4/30 0030.
 */
public class AioServerDemo {
    private static CountDownLatch latch;

    public static void startServer(){
        try {
            final AsynchronousServerSocketChannel asynchronousServerSocketChannel = AsynchronousServerSocketChannel.open();
            asynchronousServerSocketChannel.bind(new InetSocketAddress(8999));
            latch = new CountDownLatch(1);

            asynchronousServerSocketChannel.accept(null,new CompletionHandler<AsynchronousSocketChannel,Void>(){
                public void completed(AsynchronousSocketChannel ch, Void attachment) {
                    asynchronousServerSocketChannel.accept(attachment,this);
                    operate(ch);
                }

                public void failed(Throwable exc, Void attachment) {
                    latch.countDown();
                }
            });

            latch.await();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void operate(AsynchronousSocketChannel ch){
        ByteBuffer byteBuffer = ByteBuffer.allocate(40);
        try {
            int size = ch.read(byteBuffer).get();
            while (size>0){
                byteBuffer.flip();
                Charset charset = Charset.forName("UTF-8");
                System.out.println(charset.newDecoder().decode(byteBuffer));
                size = ch.read(byteBuffer).get();
            }
            ch.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        startServer();
    }
}
